package com.ruoyi.project.filemgr.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.filemgr.domain.Filemgr;
import com.ruoyi.project.filemgr.domain.ShareMonitor;
import com.ruoyi.project.filemgr.domain.Sharemgr;
import com.ruoyi.project.filemgr.service.IFilemgrService;
import com.ruoyi.project.filemgr.service.IShareMonitorService;
import com.ruoyi.project.filemgr.service.ISharemgrService;
import com.ruoyi.project.system.service.ISysUserService;

/**
 * 分享管理Controller
 * 
 * @author filemgr
 * @date 2024-02-02
 */
@RestController
@RequestMapping("/filemgr/sharemgr")
public class SharemgrController extends BaseController {
    @Autowired
    private ISharemgrService sharemgrService;
    @Autowired
    private IFilemgrService filemgrService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IShareMonitorService shareMonitorService;

    /**
     * 查询分享管理列表
     */
    @PreAuthorize("@ss.hasPermi('filemgr:sharemgr:list')")
    @GetMapping("/list")
    public TableDataInfo list(Sharemgr sharemgr) {
        startPage();
        if (null != sharemgr.getApplyUserId()) {
            sharemgr.setApplyUserId(sharemgr.getApplyUserId());
        } else {
            sharemgr.setUserId(getUserId());
            sharemgr.setShareUserId(getUserId());
        }
        List<Sharemgr> list = sharemgrService.selectSharemgrList(sharemgr);
        for (Sharemgr sharemgr2 : list) {
            sharemgr2.setFilemgr(filemgrService.selectFilemgrById(sharemgr2.getFileId()));
        }
        return getDataTable(list);
    }

    /**
     * 导出分享管理列表
     */
    @PreAuthorize("@ss.hasPermi('filemgr:sharemgr:export')")
    @Log(title = "分享管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Sharemgr sharemgr) {
        List<Sharemgr> list = sharemgrService.selectSharemgrList(sharemgr);
        ExcelUtil<Sharemgr> util = new ExcelUtil<Sharemgr>(Sharemgr.class);
        util.exportExcel(response, list, "分享管理数据");
    }

    /**
     * 获取分享管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('filemgr:sharemgr:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {

        Sharemgr sharemgr = sharemgrService.selectSharemgrById(id);
        ShareMonitor shareMonitor = new ShareMonitor();

        shareMonitor.setCreateTime(new Date());
        shareMonitor.setFileId(sharemgr.getFileId());
        shareMonitor.setType("5");
        shareMonitor.setTypeUserId(getUserId());
        shareMonitor.setTypeUserName(getLoginUser().getUser().getNickName());
        shareMonitor.setUserId(sharemgr.getShareUserId());
        shareMonitor.setUserName(sharemgr.getShareUserName());
        Filemgr filemgr = filemgrService.selectFilemgrById(sharemgr.getFileId());
        shareMonitor.setFilename(filemgr.getName());
        shareMonitorService.insertShareMonitor(shareMonitor);
        sharemgr.setFilemgr(filemgrService.selectFilemgrById(sharemgr.getFileId()));

        return success(sharemgr);
    }

    /**
     * 新增分享管理
     */
    @PreAuthorize("@ss.hasPermi('filemgr:sharemgr:add')")
    @Log(title = "分享管理", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional
    public AjaxResult add(@RequestBody Sharemgr sharemgr) {
        if ("2".equals(sharemgr.getType())) {
            sharemgr.setUserName(userService.selectUserById(sharemgr.getUserId()).getNickName());
        }
        sharemgr.setApplyUserName(userService.selectUserById(sharemgr.getApplyUserId()).getNickName());
        sharemgr.setShareUserName(getLoginUser().getUser().getNickName());
        sharemgr.setShareUserId(getUserId());

        ShareMonitor shareMonitor = new ShareMonitor();

        shareMonitor.setCreateTime(new Date());
        shareMonitor.setFileId(sharemgr.getFileId());
        shareMonitor.setType("2");
        shareMonitor.setTypeUserId(getUserId());
        shareMonitor.setTypeUserName(getLoginUser().getUser().getNickName());
        shareMonitor.setUserId(sharemgr.getShareUserId());
        shareMonitor.setUserName(sharemgr.getShareUserName());
        Filemgr filemgr = filemgrService.selectFilemgrById(sharemgr.getFileId());
        shareMonitor.setFilename(filemgr.getName());
        shareMonitorService.insertShareMonitor(shareMonitor);

        return toAjax(sharemgrService.insertSharemgr(sharemgr));
    }

    /**
     * 修改分享管理
     */
    @PreAuthorize("@ss.hasPermi('filemgr:sharemgr:edit')")
    @Log(title = "分享管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional
    public AjaxResult edit(@RequestBody Sharemgr sharemgr) {

        ShareMonitor shareMonitor = new ShareMonitor();

        shareMonitor.setCreateTime(new Date());
        shareMonitor.setFileId(sharemgr.getFileId());
        shareMonitor.setType("4");
        shareMonitor.setTypeUserId(getUserId());
        shareMonitor.setTypeUserName(getLoginUser().getUser().getNickName());
        shareMonitor.setUserId(sharemgr.getShareUserId());
        shareMonitor.setUserName(sharemgr.getShareUserName());
        Filemgr filemgr = filemgrService.selectFilemgrById(sharemgr.getFileId());
        shareMonitor.setFilename(filemgr.getName());
        shareMonitorService.insertShareMonitor(shareMonitor);

        return toAjax(sharemgrService.updateSharemgr(sharemgr));
    }

    /**
     * 删除分享管理
     */
    @PreAuthorize("@ss.hasPermi('filemgr:sharemgr:remove')")
    @Log(title = "分享管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        Arrays.asList(ids).stream().forEach(ele -> {
            Sharemgr sharemgr = sharemgrService.selectSharemgrById(ele);
            ShareMonitor shareMonitor = new ShareMonitor();
            shareMonitor.setCreateTime(new Date());
            shareMonitor.setFileId(sharemgr.getFileId());
            shareMonitor.setType("3");
            shareMonitor.setTypeUserId(getUserId());
            shareMonitor.setTypeUserName(getLoginUser().getUser().getNickName());
            shareMonitor.setUserId(sharemgr.getShareUserId());
            shareMonitor.setUserName(sharemgr.getShareUserName());
            Filemgr filemgr = filemgrService.selectFilemgrById(sharemgr.getFileId());
            shareMonitor.setFilename(filemgr.getName());
            shareMonitorService.insertShareMonitor(shareMonitor);
        });

        return toAjax(sharemgrService.deleteSharemgrByIds(ids));
    }

    @GetMapping("/download")
    public void download(Long shareId, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Sharemgr sharemgr = sharemgrService.selectSharemgrById(shareId);
        if (null == sharemgr) {
            throw new Exception("该资源不存在，不允许下载。 ");
        }
        if (!"3".equals(sharemgr.getStatus())) {
            throw new Exception("该资源未审批通过，不允许下载。 ");
        }
        if ("2".equals(sharemgr.getType()) && !getUserId().equals(sharemgr.getUserId())) {
            throw new Exception("你无权限下载该资源，不允许下载。 ");
        }
        if ("2".equals(sharemgr.getTimeType()) && new Date().after(sharemgr.getDeadline())) {
            throw new Exception("该资源已过期，不允许下载。 ");
        }
        Filemgr filemgr = filemgrService.selectFilemgrById(sharemgr.getFileId());
        if (null == filemgr) {
            throw new Exception("文件不存在，不允许下载。 ");
        }

        if (!FileUtils.checkAllowDownload(filemgr.getUrl())) {
            throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", filemgr.getUrl()));
        }

        ShareMonitor shareMonitor = new ShareMonitor();

        shareMonitor.setCreateTime(new Date());
        shareMonitor.setFileId(sharemgr.getFileId());
        shareMonitor.setShareId(shareId);
        shareMonitor.setType("1");
        shareMonitor.setTypeUserId(getUserId());
        shareMonitor.setTypeUserName(getLoginUser().getUser().getNickName());
        shareMonitor.setUserId(sharemgr.getShareUserId());
        shareMonitor.setUserName(sharemgr.getShareUserName());
        shareMonitor.setFilename(filemgr.getName());
        shareMonitorService.insertShareMonitor(shareMonitor);
        try {

            // 本地资源路径
            String localPath = RuoYiConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(filemgr.getUrl(), Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        } catch (Exception e) {
        }
    }
}
